package lab.dexter.bbsreader.managers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lab.dexter.bbsreader.ListBrowser;
import lab.dexter.bbsreader.ListManager;
import lab.dexter.bbsreader.NewSMTHHttpClient;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import lab.dexter.bbsreader.R;

public class FocusTopicsManager extends ListManager {
	public static final String PARAM_URL = "URL";
	public static final String PARAM_SECTION = "SECTION";
	
	public String suffix;
	
	private class TopicItem {
		public String title;
		public String board;
		public String title_link;
		public String board_link;
		
		public TopicItem(String title_, String board_, String title_link_, String board_link_) {
			title = title_;
			board = board_;
			title_link = title_link_;
			board_link = board_link_;
		}
		
		public String getBoardID() {
			return board_link.substring(board_link.lastIndexOf('=') + 1);
		}
		
		public String getPostID() {
			return title_link.substring(title_link.lastIndexOf('=') + 1);
		}
		
		public String toString() {
			return board + ":" + title;
		}
	}
	
	private Pattern pattern_focus_topic;
	private List<TopicItem> topics;
	private String url;
	
	private final String REGEXP = 
		"<tr\\s+class=\"bgf\"><td>([0-9]*)</td><td><a\\s+href=\"([^\"]+)\"[^>]+>([^<]+)(<[^>]+>){3}<a\\s+href=\"([^\"]+)\"[^>]+>([^<]+)";
	
	public FocusTopicsManager(Context context, Intent intent) {
		super(context, intent);
		topics = new ArrayList<TopicItem>();
		pattern_focus_topic = Pattern.compile(REGEXP);
		url = intent.getStringExtra(FocusTopicsManager.PARAM_URL);
		suffix = intent.getStringExtra(FocusTopicsManager.PARAM_SECTION);
	}
	
	@Override
	public int update() {
		try {
			NewSMTHHttpClient.getClient().fetchData(url, this);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public boolean onItemClick(int position) {
		Intent intent = new Intent(mContext, ListBrowser.class);
		intent.setAction(Intent.ACTION_VIEW);
		intent.putExtra(ListBrowser.MGR, ListBrowser.MGR_POST);
		intent.putExtra(PostManager.PARAM_BOARD, topics.get(position).getBoardID());
		intent.putExtra(PostManager.PARAM_INITIAL_ID, topics.get(position).getPostID());
		mContext.startActivity(intent);
		return false;
	}

	public void dataProcessor(HttpEntity entity) {
		try {
			// stupid server massed up the charset header, so we do the decoding manually
			//content = EntityUtils.toString(entity);
			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
			StringBuilder builder = new StringBuilder();
			String line = null;
			while((line = reader.readLine()) != null) {
				builder.append(line);
			}
			Matcher matcher = pattern_focus_topic.matcher(builder.toString());
			
			topics.clear();
			while(matcher.find()) {
				String title = matcher.group(6);
				String board = matcher.group(3);
				String title_link = matcher.group(5);
				String board_link = matcher.group(2);
				topics.add(new TopicItem(title, board, title_link, board_link));
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public boolean areAllItemsEnabled() {
		return true;
	}

	public boolean isEnabled(int position) {
		return true;
	}

	public int getCount() {
		return topics.size();
	}

	public Object getItem(int position) {
		return topics.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public int getItemViewType(int position) {
		return 0;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View view = convertView;
		if(view == null) {
			LayoutInflater vi = (LayoutInflater)(mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
            view = vi.inflate(R.layout.double_row_topic_item, null);
		}
		TopicItem it = topics.get(position);
		if(it != null) {
			TextView tv = (TextView)view.findViewById(R.id.title);

			if (tv != null) {
				tv.setText(it.title);
			}
			
			TextView meta = (TextView)view.findViewById(R.id.meta_info);
			
			if (meta != null) {
				meta.setText((position + 1) + " " + it.board);
			}
		}
		return view;
	}

	public int getViewTypeCount() {
		return 1;
	}

	@Override
	public int getContextMenuResource() {
		return R.menu.focus_topic_context_menu;
	}
	
	@Override
	public boolean hasContextMenu() {
		return true;
	}
	
	@Override
	public void onContextItemSelected(MenuItem item) {
		int id = item.getItemId();
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		//String text = null;
		switch(id) {
		case R.id.open_article:// open article
			//text = topics.get((int)info.id).title;
			this.onItemClick(info.position);
			break;
		case R.id.open_board:// open board
			//text = topics.get((int)info.id).board;
			Intent intent = new Intent(mContext, ListBrowser.class);
			intent.setAction(Intent.ACTION_VIEW);
			intent.putExtra(ListBrowser.MGR, ListBrowser.MGR_BOARD_POSTS);
			intent.putExtra(BoardPostsManager.PARAM_BOARD, topics.get(info.position).getBoardID());
			intent.putExtra(BoardPostsManager.PARAM_VIEW_MODE, BoardPostsManager.PARAM_VIEW_MODE_TOPIC);
			mContext.startActivity(intent);
			break;
		}
		
		//Toast.makeText(mContext.getApplicationContext(), text, Toast.LENGTH_SHORT).show();
	}
	
	@Override
	public String getTitleSuffix() {
		return suffix;
	}
}
